<?php
/**
 * AppController using for customize default controller of CakePHP,
 * if want changing any default behavior CakePHP controller, do on this page
 *
 * @author Dat Nguyen <datnt@evolable.asia>
 */
class AppController extends Controller {
	//Helper will be used in views
	var $helpers = array('Form', 'Html', 'Javascript', 'Time', 'User', 'Session', 'Paginator' => array('ajax' => 'CustomHtml'));
	var $components = array(
		'CustomAuth' => array(
			'authorize' => 'controller',
			'loginRedirect' => array(
				'admin' => false,
				'controller' => 'users',
				'action' => 'mypage'
			),
			'fields' => array(
				'username' => 'email',
				'password' => 'password'
			),
			'userScope' => array(
				'User.del_flg' => 0
			),
			'loginError' => Messages::invalid_account_specified ,
			'authError' => Messages::you_dont_have_the_right_permission,
			//'userModel' => 'Account',
			'loginAction' => array(
				'controller' => 'users',
				'action' => 'signin',
				'plugin' => false,
				'admin' => true,
			),
			'logoutRedirect' => array(
				'admin' => false,
				'controller' => 'course',
				'action' => 'index'
			),
			'autoRedirect' => false,
		),
		'Session', 'RequestHandler', 'Email');

	var $actionSecure = array();
	
	function beforeFilter() {
		parent::beforeFilter();
		Configure::load('general');
		if (isset ($this->params['admin']) && $this->params['admin']) {
			$this->_forceSSL();
			$this->_setAdminAuth();
			$this->layout = 'admin';
		} else {
			$this->actionSecure = array('signin', 'signup', 'password', 'payment', 'facebookSignup', 'facebookNew', 'facebook', 'logout', 'setting', 'mypage', 'account', 'profile', 'enter');
			if (!isset($this->params['requested'])) {
				if(in_array($this->action, $this->actionSecure)){
					$this->_forceSSL();
				}else {
					$this->_unForceSSL();
				}
			}
			$this->_setUserAuth();
		}
		
		$this->CustomAuth->userScope = array(
			$this->CustomAuth->userModel.'.del_flg' => 0
		);
		if (isset($this->params['requested'])) {
			$this->CustomAuth->allow('*');
		}
		$this->set(array(
			'title_for_layout' => 'Adams Campus',
			'hideBanner' => true,
		));
	}

	/**
	 * force to SSL 
	 */
	function _forceSSL(){
		if(!$this->RequestHandler->isSSL()){
			if (!$url = env('REQUEST_URI')) {
				$url = $this->here;
			}
			$this->redirect('https://' . env('SERVER_NAME') . $url);
		}
	}
	/**
	 * force to non SSL
	 */
	function _unForceSSL(){
		if(!$this->RequestHandler->isAjax() && $this->RequestHandler->isSSL()){
			if (!$url = env('REQUEST_URI')) {
				$url = $this->here;
			}
			$this->redirect('http://' . env('SERVER_NAME') . $url);
		}
	}
	/**
	 * author
	 * @return type
	 */
	public function isAuthorized() {
		//return true;
		$role = $this->CustomAuth->user('role');
		$neededRole = null;
		$prefix = !empty($this->params['prefix']) ? $this->params['prefix'] : null;
		if( !(empty($prefix)) && in_array($prefix, Configure::read('Routing.prefixes'))){
			$neededRole = $prefix;
		}
		$roles = Configure::read('roles');
		return (strcasecmp($role, 'admin') == 0 || in_array($role, $roles) || strcasecmp($role, $neededRole) == 0);
		
	}

	public function _checkAuthor($controller , $action){
		$role = $this->CustomAuth->user('role');
		if($role !='user'){
			$this->redirect(array(
				$role => true,
				'controller' => $controller,
				'action' => $action
			));
		}
	}
	
	private function _setAdminAuth()
	{
		$this->CustomAuth->userModel = 'Member';
		$this->CustomAuth->fields = array(
			'username' => 'login_id',
			'password' => 'password'
		);
		$this->CustomAuth->loginAction = array(
				'controller' => 'members',
				'action' => 'signin',
				'plugin' => false,
				'admin' => true,
			);
	}
	
	private function _setUserAuth(){
		$this->CustomAuth->userModel = 'User';
		$this->CustomAuth->fields = array(
			'username' => 'email',
			'password' => 'password'
		);
		$this->CustomAuth->loginAction = array(
				'controller' => 'users',
				'action' => 'signin',
				'plugin' => false,
				'admin' => false,
			);
	}


	/**
	 * Initial email configuration
	 */
	function _initEmail() {
		$emailConfig = Configure::read('email');

		$this->Email->smtpOptions = $emailConfig;

		$this->Email->from = $emailConfig['from'];

		$this->Email->sendAs = 'html';

		$this->Email->delivery = $emailConfig['delivery'];
	}

	/*
	 * count enterdClassNumber
	 */
	function _getEnteredClassNumber($userId = null)
	{
		if (!isset ($userId)) {
			$userId = $this->CustomAuth->user('id');
		}
		$this->loadModel('EnteredCourse');
		$countOptions['conditions'] = array(
			'EnteredCourse.user_id' => $userId,
			'EnteredCourse.del_flg' => 0
		);
		$countOptions['joins'] = array(
			array(
				'table' => 'courses_detail',
				'alias' => 'CoursesDetail',
				'type' => 'inner',
				'conditions' => array(
					'EnteredCourse.detail_id = CoursesDetail.id',
					'CoursesDetail.opening_date <=' => date('Y-m-d H:i:s')
				)
			)
		);
		$enteredClassNumber = $this->EnteredCourse->find('count', $countOptions);
		return $enteredClassNumber;
	}

	/**
	 * count attend class
	 */
		/*
	 * count enterdClassNumber
	 */
	function _getAttendClassNumber($userId = null)
	{
		if (!isset ($userId)) {
			$userId = $this->CustomAuth->user('id');
		}
		$this->loadModel('EnteredCourse');
		$countOptions['conditions'] = array(
			'EnteredCourse.user_id' => $userId,
			'EnteredCourse.del_flg' => 0
		);
		$countOptions['joins'] = array(
			array(
				'table' => 'courses_detail',
				'alias' => 'CoursesDetail',
				'type' => 'inner',
				'conditions' => array(
					'EnteredCourse.detail_id = CoursesDetail.id',
					'CoursesDetail.opening_date >' => date('Y-m-d H:i:s')
				)
			)
		);
		$enteredClassNumber = $this->EnteredCourse->find('count', $countOptions);
		return $enteredClassNumber;
	}
	
	function beforeRender() {
		$this->_updateUserStatus();
		$messages = new ReflectionClass('Messages');
		$this->set(array(
			'userLogon' => $this->CustomAuth->user(),
			'messages' => $messages->getConstants(),
		));
	}

	function _updateUserStatus($forceUpdate = false) {
		$userId = $this->CustomAuth->user('id');
		if (!$userId) {
			return;
		}
		$this->loadModel('Course');

		if ($this->Session->check('User.pass_courses')) {
			$courses = $this->Course->getPassCourse($userId);
			$sessionCourses = array();
			foreach ($courses as $course) {
				$sessionCourses[$course['Course']['id']] = $course;
			}
			$this->Session->write('User.pass_courses', $sessionCourses);
		}

		$time = strtotime(sprintf('-%d minutes', Configure::read('UserStatus.user_status_expire_time')));
		if ($forceUpdate ||
			!$this->Session->check('User.courses') ||
			$this->Session->read('UserStatus.updated') <= $time) {
			$courses = $this->Course->getWaitingCourse($userId);
			$sessionCourses = array();
			foreach ($courses as $course) {
				$sessionCourses[$course['Course']['id']] = $course;
			}
			$this->Session->write('User.courses', $sessionCourses);
			$this->Session->write('UserStatus.updated', time());
		}
	}
}